package com.yisu.expressway.trafficViolation;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.method.ReplacementTransformationMethod;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.yisu.expressway.R;
import com.yisu.expressway.activity.BaseActivity;
import com.yisu.expressway.model.CarIllegalInfo;
import com.yisu.expressway.model.CarTypeObj;
import com.yisu.expressway.network.ApiClientHelper;
import com.yisu.expressway.network.ApiResult;
import com.yisu.expressway.network.ApiSetting;
import com.yisu.expressway.settings.AppConstant;
import com.yisu.expressway.ui.SingleButtonAlertDialog;
import com.yisu.expressway.utils.StringUtil;
import com.yisu.expressway.utils.ToastUtil;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;

public class CarIlegalQueryActivity extends BaseActivity implements AdapterView.OnItemSelectedListener{

    @Bind(R.id.edt_car_number)
    protected EditText mEdt_CarNum;
    @Bind(R.id.edt_car_framework_number)
    protected EditText mEdt_CarFramworkNum;
    @Bind(R.id.edt_engine_number)
    protected EditText mEdt_EngineNum;
    @Bind(R.id.sp_car_type)
    protected Spinner mSp_CarType;

    private final static String CAR_TYPE_LIST = "car_type_list";
    private ArrayList<CarTypeObj> mCarTypeList = new ArrayList<>();
    private CarTypeObj mSelectCarTypeItem;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_car_ilegal_query);
        initView(getIntent());
    }

    private void initView(Intent intent){
        setTitle(R.string.query_violation);
        if(intent != null){
            mCarTypeList = (ArrayList<CarTypeObj>)intent.getSerializableExtra(CAR_TYPE_LIST);
            if(mCarTypeList == null || mCarTypeList.size() == 0){
                getCarTypeList();
            }

            initCarTypeSpinner();

        }
        ToUpperCase toUpperCase = new ToUpperCase();
        mEdt_CarNum.setTransformationMethod(toUpperCase);
        mEdt_EngineNum.setTransformationMethod(toUpperCase);
        mEdt_CarFramworkNum.setTransformationMethod(toUpperCase);
    }

    public static void launch(Context context, ArrayList<CarTypeObj> list){
        Intent mIntent = new Intent(context,CarIlegalQueryActivity.class);
        mIntent.putExtra(CAR_TYPE_LIST,list);
        context.startActivity(mIntent);
    }

    private void initCarTypeSpinner(){
        if(mCarTypeList == null || mCarTypeList.size() == 0){
            return;
        }
        int length = mCarTypeList.size();
        String[] branchNameArray = new String[length];
        for (int i = 0; i < length; i++) {
            branchNameArray[i] = mCarTypeList.get(i).name;
        }
        ArrayAdapter<String> mAdapter = new ArrayAdapter<>(this,R.layout.custom_spinner_selected_view, branchNameArray);
        mAdapter.setDropDownViewResource(R.layout.custom_spinner_drop_view);
        mSp_CarType.setAdapter(mAdapter);
        mSp_CarType.setOnItemSelectedListener(this);
        mSp_CarType.setSelection(1);
    }

    @OnClick(R.id.btn_query)
    protected void clickToQuery(){
        queryCarIllegalRecord();
    }

    /**
     * 获取汽车类型列表
     */
    private void getCarTypeList(){
        ApiClientHelper.getApi(ApiSetting.getCarTypeList(), new TypeToken<ArrayList<CarTypeObj>>() {
                },
                new Response.Listener<ApiResult<ArrayList<CarTypeObj>>>() {
                    @Override
                    public void onResponse(final ApiResult<ArrayList<CarTypeObj>> result) {
                        if (!result.success) {
                            return;
                        }

                        mCarTypeList = result.getResult();
                        initCarTypeSpinner();
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {

                    }
                }, this);
    }

    private void queryCarIllegalRecord(){

        if(!checkIsInfoCorrect()){
            return;
        }

        Map<String, Object> params = new HashMap();
        params.put("carCode",mEdt_CarFramworkNum.getText().toString());
        params.put("carEngineCode",mEdt_EngineNum.getText().toString());
        params.put("carNumber",mEdt_CarNum.getText().toString());
        params.put("carType",mSelectCarTypeItem.code);

        showLoading();

        ApiClientHelper.postApi(ApiSetting.queryCarBreakRule(), new TypeToken<ArrayList<CarIllegalInfo>>() {
        }, new JSONObject(params), new Response.Listener<ApiResult<ArrayList<CarIllegalInfo>>>() {
            @Override
            public void onResponse(ApiResult<ArrayList<CarIllegalInfo>> result) {

                dismissLoading();

                if (!result.success) {
                    String errorMsg = result.getMsg();
                    if(result.getCode() == AppConstant.QUERY_TIMES_LIMITED){
                        SingleButtonAlertDialog mDialog = new SingleButtonAlertDialog(CarIlegalQueryActivity.this);
                        mDialog.show();
                        mDialog.setContentText(errorMsg);
                    }else {
                        ToastUtil.displayLongToastMsg(CarIlegalQueryActivity.this, errorMsg);
                    }
                    return;
                }

                ArrayList<CarIllegalInfo> mList = result.getResult();
                if(mList != null && mList.size() > 0){
                     CarIllegalRecordActivity.launch(CarIlegalQueryActivity.this,mList,mEdt_CarNum.getText().toString());
                }else{
                    ToastUtil.displayLongToastMsg(CarIlegalQueryActivity.this, R.string.no_illegal_record);
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                dismissLoading();
                ToastUtil.displayShortToastMsg(CarIlegalQueryActivity.this, volleyError.getMessage());
            }
        }, this);

    }

    private boolean checkIsInfoCorrect(){

        boolean infoCorrect = true;

        if(StringUtil.isNullOrEmpty(mEdt_CarNum.getText().toString()) || StringUtil.isNullOrEmpty(mEdt_CarFramworkNum.getText().toString()) ||
                StringUtil.isNullOrEmpty(mEdt_EngineNum.getText().toString())){
            infoCorrect = false;
            ToastUtil.displayShortToastMsg(this,R.string.info_should_no_empty);
        }

        return infoCorrect;
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()){
            case R.id.sp_car_type:
                mSelectCarTypeItem = mCarTypeList.get(position);
                break;
            default:
                break;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    private class ToUpperCase extends ReplacementTransformationMethod {
        private final char[] LOWER = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
        private final char[] UPPER = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
        @Override
        protected char[] getOriginal() {
            return LOWER;
        }

        @Override
        protected char[] getReplacement() {
            return UPPER;
        }

    }
}
